package cn.itcast.shiro;

import cn.hutool.extra.spring.SpringUtil;
import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {

    @Reference
    private ModuleService moduleService;
    @Autowired
    private UserDao userDao;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证登录");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String email = usernamePasswordToken.getUsername();
        User user = userDao.findByEmail(email);
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("授权角色权限");
        User user = (User) principals.getPrimaryPrincipal();
        List<Module> modules = moduleService.findModuleListByUser(user);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        modules.forEach(module -> {
            authorizationInfo.addStringPermission(module.getName());
        });
        System.out.println("当前登录人："+user.getUserName()+"，具有的权限："+authorizationInfo.getStringPermissions());
        return authorizationInfo;
    }


}
